package com.hnist.empdemo.utils;

import java.util.prefs.Preferences;

/**
 * 凭据管理器，用于管理用户的登录凭据存储
 */
public class CredentialManager {
    private static final String PREFS_NODE = "com/hnist/empdemo";
    private static final String USERNAME_KEY = "username";
    private static final String PASSWORD_KEY = "password";
    private static final String AUTO_LOGIN_KEY = "autoLogin";
    private static final String AUTO_LOGIN_COUNT_KEY = "autoLoginCount";
    private static final int MAX_AUTO_LOGIN_ATTEMPTS = 3; // 设置最大自动登录次数
    
    private Preferences prefs;
    
    public CredentialManager() {
        this.prefs = Preferences.userRoot().node(PREFS_NODE);
    }
    
    /**
     * 保存用户凭据
     * @param username 用户名
     * @param password 密码
     */
    public void saveCredentials(String username, String password) {
        prefs.put(USERNAME_KEY, username);
        prefs.put(PASSWORD_KEY, password);
        try {
            prefs.flush(); // 确保立即写入
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveAutoLoginStatus(boolean autoLogin) {
        prefs.putBoolean(AUTO_LOGIN_KEY, autoLogin);
        try {
            prefs.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 加载保存的用户凭据
     * @return 包含用户名和密码的字符串数组，[0]为用户名，[1]为密码
     */
    public String[] loadCredentials() {
        String username = prefs.get(USERNAME_KEY, "");
        String password = prefs.get(PASSWORD_KEY, "");
        return new String[]{username, password};
    }
    
    /**
     * 清除保存的用户凭据
     */
    public void clearCredentials() {
        prefs.remove(USERNAME_KEY);
        prefs.remove(PASSWORD_KEY);
    }
    
    /**
     * 检查是否存在保存的凭据
     * @return 如果存在保存的凭据返回true，否则返回false
     */
    public boolean hasSavedCredentials() {
        String username = prefs.get(USERNAME_KEY, "");
        String password = prefs.get(PASSWORD_KEY, "");
        return !username.isEmpty() && !password.isEmpty();
    }

    public boolean getAutoLoginStatus() {
        return prefs.getBoolean(AUTO_LOGIN_KEY, false);
    }

    public void incrementAutoLoginCount() {
        int currentCount = prefs.getInt(AUTO_LOGIN_COUNT_KEY, 0);
        prefs.putInt(AUTO_LOGIN_COUNT_KEY, currentCount + 1);
        try {
            prefs.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean canAutoLogin() {
        int count = prefs.getInt(AUTO_LOGIN_COUNT_KEY, 0);
        return count < MAX_AUTO_LOGIN_ATTEMPTS;
    }

    public void resetAutoLoginCount() {
        prefs.putInt(AUTO_LOGIN_COUNT_KEY, 0);
        try {
            prefs.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}